package top.xia17.plugins.fast.common.spring.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.HandlerInterceptor;
import top.xia17.plugins.fast.common.utils.web.RequestUtil;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 请求信息打印器
 * @author xia17
 */
@Slf4j
public class VisitInterceptor implements HandlerInterceptor {


    /**
     *
     * @param request 请求
     * @param response 返回
     * @param handler /
     * @return /
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             @NonNull HttpServletResponse response,@NonNull Object handler){
        log.info("-----------------------------------------------------------------------------------------------------------");
        //从request中获取http请求的url/请求的方法类型／响应该http请求的类方法／IP地址／请求中的参数
        log.info("[URI]: {}",request.getRequestURI());
        log.info("[path]: {}",request.getServletPath());
        log.info("[Method]: {}" + request.getMethod() + "}");
        log.info("[queryString]: {}" , request.getQueryString());
        Map<String, String[]> map = request.getParameterMap();
        map.forEach((k,v)->log.info("[请求参数{}] = {}",k,String.join(",",v)));
        //ip
        log.info("[ip] = {" + request.getRemoteAddr() + "}");
        log.info("[访客ip] = {}", RequestUtil.getIp(request));
        log.info("-----------------------------------------------------------------------------------------------------------");
        return true;
    }

    /**
     * 打印参数
     * @param name 名
     * @param values 值
     */
    private void showParams(String name , String[] values){
        String params = String.join("", values);
        StringBuilder sb = new StringBuilder();
        if (values != null && values.length != 0){
            for (int i = 0; i < values.length; i++) {
                sb.append(values[i]);
                if (i != values.length -1){
                    sb.append(",");
                }
            }
        }
        log.info("{}  : {}",name,sb);
    }

}
